package com.shell.customer.accreditation.rx;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.shell.bee.base.utils.JsonUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.base.service.CusExtraService;
import com.shell.customer.po.CusExtra;
import com.shell.customer.po.CusRec;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;

@Component
public class BroadcastAfterAccreditSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private CusExtraService pubCusExtraService;
	@Value("${customer.broadcast.serviceApp:}")
	private String serviceApp;
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	@Autowired
	RestTemplate restTemplate;

	public void onApplicationEvent(AccreditEvent event) {
		AccreditationVo accreditationVo = event.getAccreditationVo();
		CusRec cus = accreditationVo.getCustomerC();
		CusExtra cusExtra = (CusExtra) this.pubCusExtraService.selectByKey(cus.getCusId());
		if (StringUtil.empty(this.serviceApp)) {
			this.logger.info("������������������������������������");
			return;
		}
		String[] serviceList = this.serviceApp.split(",");

		MultiValueMap<String, Object> map = new LinkedMultiValueMap();
		try {
			map.add("cus", JsonUtil.toJson(cus));
			map.add("cusExtra", JsonUtil.toJson(cusExtra));
			map.add("finId", CommonDataUtil.getCurEntId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		ServiceInstance serviceInstance = null;
		for (String serviceName : serviceList) {
			serviceInstance = this.loadBalancerClient.choose(serviceName);
			if (serviceInstance == null) {
				throw new RuntimeException("��������������������������.");
			}
			this.logger.info("��������--------->" + serviceInstance.getUri().toString() + "/" + serviceName
					+ "/afterCusAccredit");
			this.restTemplate.postForObject(
					serviceInstance.getUri().toString() + "/" + serviceName + "/afterCusAccredit", map, Map.class,
					new Object[0]);
		}
	}
}
